/*Aitor Gonzalez Aguirre 	(NIA: 47757) aitor.gonzalez02@campus.upf.edu
Agustin Marziani 	(NIA: 69236) agustin.marziani01@campus.upf.edu*/

//global info about the light
uniform vec3 light_position[2];

uniform vec3 light_color[2];

//Colores
uniform vec3 ambient_factor;
uniform vec3 diffuse_factor;
uniform vec3 specular_factor;

//Intensidades
uniform float ambient_intensity;
uniform float diffuse_intensity;
uniform float specular_intensity;

//Glossiness
uniform float glossiness;

//this will store the color for the pixel shader
varying vec3 pixel_color;

//Ojo de la camara
uniform vec3 camera_eye;

uniform mat4 model;
uniform mat4 normal_model;
uniform mat4 mvp;



void main()
{	
	//calcule the normal (N) in world space (the normal_model is like the model but without traslation)
	vec3 normal = (normal_model * vec4(gl_Normal,1.0) ).xyz;
	
	//calcule the vertex (P) in world space (because the light position is in world space and the vertex comes in local space)
	vec3 vertex_pos = (model * gl_Vertex).xyz;

	//calcule the eye (V)
	vec3 eye_vector = camera_eye - vertex_pos;
	eye_vector = normalize(eye_vector);
	
	
	//Calculamos los componentes necesarios
	vec3 light_vector[2], reflected_vector[2];
	float LdotN[2], RdotV[2];
	
	for (int i=0; i<2; i++) {
		//calcule the light_vector (L)
		light_vector[i] = light_position[i] - vertex_pos;
		//normalize the light vector
		light_vector[i] = normalize(light_vector[i]);
		
		//calcule the NdotL
		LdotN[i] = dot (light_vector[i], normal);
		//avoid negative values (it doesnt makes sense to have negative light)
		if (LdotN[i] < 0.0) LdotN[i] = 0.0;
		
		//Calcule the reflected vector (R)
		reflected_vector[i] = reflect(light_vector[i], normal);
		reflected_vector[i] = -1 * reflected_vector[i];
		
		//calcule the RdotV
		RdotV[i] = dot (reflected_vector[i], eye_vector);
		
		//avoid negative values (it doesnt makes sense to have negative light)
		if (RdotV[i] < 0.0) RdotV[i] = 0.0;
	}
	
	
	//////////////////////////////FORMULA//////////////////////////////////////////
	vec3 ambient_color, diffuse_color[2], specular_color[2], pixel_intensity[2];
	
	ambient_color = ambient_factor * ambient_intensity;
	
	pixel_color = ambient_color;
	for (int i=0; i<2; i++) {
		diffuse_color[i] = diffuse_factor * LdotN[i] * diffuse_intensity;
		specular_color[i] = specular_factor * pow(RdotV[i], glossiness) * specular_intensity;
		pixel_intensity[i] = diffuse_color[i] + specular_color[i];
		pixel_color += pixel_intensity[i] * light_color[i];
	}
	
	//compute the position of the vertex in screen space using the MVP
	gl_Position = mvp * gl_Vertex;
}